<?php

namespace app\controllers;

use Yii;
use app\models\ChatRecord;
use app\models\ChatSession;
use app\models\ChatRecordSearche;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * ChatRecordController implements the CRUD actions for ChatRecord model.
 */
class ChatRecordController extends Controller {
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all ChatRecord models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new ChatRecordSearche();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single ChatRecord model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ChatRecord model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new ChatRecord();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing ChatRecord model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing ChatRecord model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ChatRecord model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ChatRecord the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = ChatRecord::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionGetSessionList() {
        $ChatRecord = new ChatRecord();
        $ChatSession = new ChatSession();
        $data = array(
            'code' => 1,
            'msg' => '获取列表成功！'
        );
        /* 获取用户名 */
        $userInfo = Yii::$app->getUser()->identity->attributes;
        /* 获取当前会话列表 */
        $condition = array(
            'receiver' => $userInfo['id'],
            'state' => 1
        );
//        $field = array(
//            'sender',
//            'sender_name',
//            'message_number'
//        );
        $order = 'update_time desc';
        $result = $ChatSession->getSession($condition);

        $data['currentSessionList'] = array();
        if (!empty($result)) {
            $currentSessionList = array();
            foreach ($result as $k => $v) {
                $tmp['userid'] = $v['sender'];
                $tmp['username'] = $v['sender_name'];
                $tmp['messageNumber'] = $v['message_number'];
//                $tmp['headImage'] = sprintf("%s", $v['sender'] % 10000, $v['sender']);
                $tmp['headImage'] = 'http://unsplash.it/'.($tmp['userid'] + 100).'/100/?random';

                /* 检查该用户是否在线 */
                $online = $this->isOnline($v['sender']);
                $tmp['online'] = $online ? 1 : 0;
                $currentSessionList[] = $tmp;
            }
            $data['currentSessionList'] = $currentSessionList;
            /* 关闭redis连接 */
//            if ($this->redis) {
//                $this->redis->close();
//            }
        }
        /* 获取历史会话列表 */
        $condition = array(
            'receiver' => $userInfo['id'],
            'state' => 2
        );
        $limit = array(
            'number' => 100,
            'start' => 0
        );
        $data['historySessionList'] = array();
        $result = $ChatSession->getSession($condition);
//        $result = $ChatRecord->getSessionList($condition);
        if (!empty($result)) {
            $historySessionList = array();
            foreach ($result as $k => $v) {
                $tmp['userid'] = $v['sender'];
                $tmp['username'] = $v['sender_name'];
//                $tmp['headImage'] = sprintf("%s", $v['sender'] % 10000, $v['sender']);
                $tmp['headImage'] = 'http://awb.img1.xmtbang.com/wechatmsg2015/article201505/20150518/thumb/0606514d51f94199af793192e8165c2b.jpg';

                $historySessionList[] = $tmp;
            }
            $data['historySessionList'] = $historySessionList;
        }
        echo json_encode($data);
    }

    public function actionGetSession() {
//        chat-record/get-session
        $ChatRecord = new ChatRecord();
        $time = time() - 3600 * 24;
        $time = strtotime(date('Ymd', $time)); // 获取最近前天和当天的历史记录
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $sessionId = isset($_REQUEST['sessionId']) ? trim($_REQUEST['sessionId']) : '';
        $type = isset($_REQUEST['type']) ? trim($_REQUEST['type']) : 'current';
        $userInfo = Yii::$app->getUser()->identity->attributes;
        $userid = $userInfo['id'];
        if (empty($sessionId)) {
            $data['msg'] = 'sessionId不能为空！';
            echo json_encode($data);
            return false;
        }
        $robotId = 'xxxxxxxxx';
        switch ($type) {
            case 'current':
//                $condition = "ctime >= $time and ((sender = '$sessionId' and receiver = '$userid') or (sender = '$userid' and receiver = '$sessionId') or (sender = '$sessionId' and receiver = '$robotId') or (sender = '$robotId' and receiver = '$sessionId'))";
                break;
            case 'history':
//                $condition = "sender = '$sessionId' or receiver = '$sessionId'";
                break;
            default:
                $data['msg'] = 'type错误！';
                echo json_encode($data);
                return false;
        }
        $field = array();
        $condition = ['sender'=>$sessionId];$orCondition = ['receiver'=>$sessionId];
        $result = $ChatRecord->getSession($condition,$orCondition);
        if (empty($result)) {
            $data = array(
                'code' => 1,
                'msg' => '未查询到记录',
                'res' => array()
            );
            echo json_encode($data);
            return false;
        }
        $res = array();
//        $senderHeadImage = sprintf('%s', $sessionId % 10000, $sessionId);
        $senderHeadImage = 'http://awb.img1.xmtbang.com/wechatmsg2015/article201505/20150518/thumb/0606514d51f94199af793192e8165c2b.jpg';
        foreach ($result as $k => $v) {
            $tmp['id'] = $v['id'];
            $tmp['time'] = date('Y-m-d H:i:s', $v['ctime']);
            $tmp['message'] = $v['comment'];
            $tmp['senderId'] = $v['sender'];
            $tmp['snederName'] = ($robotId == $v['sender_name']) ? '同花顺智能机器人' : $v['sender_name'];
            if ($sessionId == $v['sender']) {
                $tmp['headImage'] = $senderHeadImage;
                $tmp['userFlag'] = 0;
            } elseif ($robotId == $v['sender_name']) {
                $tmp['headImage'] = 'http://s.thsi.cn/js/m/newhelp/images/robot.png';
                $tmp['userFlag'] = 1;
            } else {
                $tmp['headImage'] = 'http://g.hiphotos.baidu.com/zhidao/wh%3D450%2C600/sign=4c33f1b70dd162d985bb6a1824ef85da/5366d0160924ab18d9105e4432fae6cd7b890bba.jpg';
                $tmp['userFlag'] = 1;
            }
            $res[] = $tmp;
        }
        $data = array(
            'code' => 1,
            'msg' => '查询成功！',
            'res' => $res
        );
        echo json_encode($data);
    }

    /* 判断用户是否在线 */

    private function isOnline($userid) {
        return true;
    }

    
    public function actionEliminateRedSpots(){
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $sender = isset($_REQUEST['userid']) ? trim($_REQUEST['userid']) : '';
        if (empty($sender)) {
            $data['msg'] = 'userid不能为空!';
            echo json_encode($data);
            return false;
        }
        $user = Yii::$app->getUser()->identity->attributes;
        $username = $user['id'];
        $condition = array(
            'sender' => $sender,
            'receiver' => $username
        );
        $ChatSession = ChatSession::updateAll(['message_number'=>0],$condition);
        if ($ChatSession) {
            $data['code'] = 1;
            $data['msg'] = '操作成功！';
        } else {
            $data['msg'] = '操作失败！';
        }
        echo json_encode($data);
    }
    
    public function actionSessionSet()
    {
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : 1; // type=1:从当前切换到历史；type=2:从历史移除；type=3:从历史移到当前
        $sender = isset($_REQUEST['userid']) ? trim($_REQUEST['userid']) : '';
        if (empty($sender)) {
            $data['msg'] = 'userid不能为空!';
            echo json_encode($data);
            return false;
        }
        
        $userInfo = Yii::$app->getUser()->identity->attributes;
        $username = $userInfo['id'];
        $condition = array(
            'sender' => $sender,
            'receiver' => $username
        );
        $value = array();
        switch ($type) {
            case '1':
                $state = 2;
                $value['message_number'] = 0;
                break;
            case '2':
                $state = 0;
                break;
            case '3':
                $state = 1;
                break;
            default:
                $data['msg'] = 'type类型错误！';
                echo json_encode($data);
                return false;
        }
        $value['state'] = $state;
        $result = ChatSession::updateAll($value, $condition);
        if ($result) {
            $data['code'] = 1;
            $data['msg'] = '操作成功！';
        } else {
            $data['msg'] = '操作失败！';
        }
        echo json_encode($data);
    }
}
